<template>
  <div>
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px">
      <el-form-item label="First Name" prop="firstName">
        <el-input v-model="ruleForm.firstName" placeholder="First Name" clearable></el-input>
      </el-form-item>
      <el-form-item label="Last Name" prop="lastName">
        <el-input v-model="ruleForm.lastName" placeholder="Last Name" clearable></el-input>
      </el-form-item>
      <el-form-item label="Address" prop="address">
        <el-input v-model="ruleForm.address" placeholder="Address" clearable></el-input>
      </el-form-item>
      <el-form-item label="City" prop="city">
        <el-input v-model="ruleForm.city" placeholder="City" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">Save</el-button>
        <el-button @click="backForm('ruleForm')">Back</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import axios from "axios";

  export default {
    data() {
      return {
        ruleForm: {
          firstName: '',
          lastName: '',
          address: '',
          city: '',
        },
        rules: {
          firstName: [
            { required: true, message: 'Can not input empty data!', trigger: 'blur' }
          ],
          lastName: [
            { required: true, message: 'Can not input empty data!', trigger: 'blur' }
          ],
          address: [
            { required: true, message: 'Can not input empty data!', trigger: 'blur' }
          ],
          city: [
            { required: true, message: 'Can not input empty data!', trigger: 'blur' }
          ],
        }
      }
    },
    methods: {
      submitForm(formName) {
        const _this = this
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$axios.put("http://localhost:9000/person", this.ruleForm).then(res=> {
              _this.$alert('Update successfully!', 'Message', {
                confirmButtonText: 'OK',
                callback: action => {
                  _this.$router.push('/nav1')
                }
              })
            }, function(err) {
              _this.$alert('Net error!', 'Message', {
                confirmButtonText: 'OK'
              })
            })
          } else {
            return false
          }
        })
      },
      backForm(formName) {
        const _this = this
        _this.$router.go(-1)
      }
    },
    created() {
      this.$axios.get("http://localhost:9000/person/" + this.$route.params.id).then(res=>{
        console.log(res)
        this.ruleForm = res.data
      })
    }
  }
</script>